<?php
//添加图片项目
if(!defined('IN_T')){
	die('hacking attempt');
}
require_once ROOT_PATH.'source/krpano/cls_pano_op.php';

$act =  Common::sfilter($_REQUEST['act']);
$input=null;
if(empty($act)){
	$input = $Json->decode(file_get_contents("php://input"));
	if (!empty($input)) {
		$act = $input['act'];
	}
}
if ($act =="add") {
	//设置该次请求超时时长，1800s
	@ini_set("max_execution_time", "1800"); 
	//兼容php-fpm设置超时
	@ini_set("request_terminate_timeout", "1800");

	$step = intval($_REQUEST['step']);
	$re['status'] = 0;
	if ($step == 1) {
		//用于参数，数量是否达到上限等验证	
		if(!function_exists('exec')){
			$re['msg'] = '系统当前不支持exec方法，无法发布！';
			echo $Json->encode($re);
			die;
		}
		if(!Transaction::get_user_projects_limit($user['pk_user_main'])){
			$re['msg'] = "你可发布的作品数量已达上限，无法再发布！";
			echo $Json->encode($re);
			die;
		}
		
		$re['status'] = 1;
		echo $Json->encode($re);
		die;

	}else if($step == 2){
		//统一下载全景图
		$pano_op = new KrOperation();
		$panos = $_REQUEST['panos'];
		$result = $pano_op->downloadFile($user['pk_user_main'],$panos,$user['pk_user_main']."/works/");
		if ($result['path']==''||empty($result['imgsmain'])) {
			$re['msg']='服务器获取图片异常，请检查目录是否可写，或者cdn配置是否正确';
		}else{
			$re['status'] = 1;
			$_SESSION['user']['pano_store'] =$result;
		}
		echo $Json->encode($re);
		die;
	}
	else if($step == 3){
		$user = $_SESSION['user'];
		//调用krpano 进行统一切图
		if (empty($user['pano_store'])||empty($user['pano_store']['path'])) {
			$re['msg']='请求超时，请重新登录';
		}else{
			$result = $user['pano_store'];
			$pano_op = new KrOperation();
			$pano_op->slicePano($result['path']); //该步骤无法判断切图是否成功
			//读取xml文件，获得相应图片的配置信息
			$xml=simplexml_load_file($result['tempdir'].'vtour/tour.xml');

			$scenes = $xml->scene;
			foreach ($scenes as $s) {
				$uuid = $s->attributes();//
				$uuid = $uuid['title'];
				$storeLevels = array();
				foreach ($result['imgsmain'] as &$iv) {
					if ($uuid ==  $iv['view_uuid']) {
						//找到对应的全景，获取全景图的level
						$levels = $s->image->level;
						foreach ($levels as $level) {
							$level_attributes = $level->attributes();
							$storeLevels[] = $level_attributes['tiledimagewidth'];
						}
						$iv['levels'] = implode(",", $storeLevels);
						break;
					}
				}
			}
			$_SESSION['user']['pano_store'] = $result;
			$re['status'] = 1;
			$re['index'] = 0 ;
			$re['filename'] = $result['imgsmain'][0]['filename'];
		}
		echo $Json->encode($re);
		die;

	}else if($step == 4){
		//前端循环请求该步骤，进行目录上传
		$pano_store = $_SESSION['user']['pano_store'];
		if (empty($pano_store)) {
			$re['msg'] = '上传异常，请重新登录，并再次上传全景图片';
			echo $Json->encode($re);
			die;
		}
		$index = intval($_REQUEST['index']);
		$pano = $pano_store['imgsmain'];
		if ($index == sizeof($pano)) {
			$re['status'] = 2;//上传全景图成功
		}else{
			//执行上传
			$pano_op = new KrOperation();
			$pano_op->uploadFile($pano_store['tempdir'].'vtour/panos/'.$pano[$index]['view_uuid'].'/',$user['pk_user_main']."/works/".$pano[$index]['view_uuid'].'/');
			$index++;
			$re['status'] = 1;
			$re['index'] =$index ;
			$re['filename'] = $pano[$index]['filename'];
		}
		echo $Json->encode($re);
		die;
	}else if($step == 5){
		//存储数据到数据库
		$params = $Json->decode(stripslashes($_REQUEST['params']));
		$atlas_id = intval($params['atlas_id']);
		$pname = Common::sfilter($params['pname']);
		if(!function_exists('exec')){
			$re['msg'] = '系统当前不支持exec方法，无法发布！';
		}
		else if(!Transaction::get_user_projects_limit($user['pk_user_main'])){
			$re['msg'] = "你可发布的作品数量已达上限，无法再发布！";
		}
		else if(mb_strlen($pname)<=0||mb_strlen($pname)>100){
			$re['msg'] = "项目名称在1到100个字符之间";
		}
		else{
			try{
				require_once ROOT_PATH.'plugin/plugin_init_function.php';
				plugin_get_plugins("edit");
				
				$Db->beginTransaction();
				if($atlas_id<=0||$Db->getCount($Base->table('atlasmain'),'pk_atlas_main',array('pk_atlas_main'=>$atlas_id,'pk_user_main'=>$user['pk_user_main']) )<=0 ){
					//没有提交图册分类
					$atlas_id = $Db->query('SELECT pk_atlas_main FROM '.$Base->table('atlasmain').' WHERE pk_user_main = '.$user['pk_user_main'].' AND atlas_type = 0','One');
					if(empty($atlas_id)){
						$atlas = array("pk_user_main"=>$user['pk_user_main'],"name"=>"默认图册","atlas_type"=>0,"create_time"=>date('Y-m-d H:i:s',Common::gmtime()));
						//初始化用户图册信息
						$atlas_id = $Db->insert($Base->table("atlasmain"),$atlas);
					}
				}
				$imgsmain = $_SESSION['user']['pano_store']['imgsmain'];
				//存储数据
				$worksmain['pk_user_main']=$user['pk_user_main'];
				$worksmain['pk_atlas_main']=$atlas_id;
				$worksmain['name'] =$pname ;
				$worksmain['thumb_path']= $imgsmain[0]['thumb_path'];
				$worksmain['view_uuid']=Common::guid(16);
				$worksmain['photo_date']=date("Y-m-d H:i:s",Common::gmtime());
				$worksmain['create_time']=date("Y-m-d H:i:s",Common::gmtime());
				$worksmain['flag_allowed_recomm']=intval($params['allow_recomm']);
				$worksmain['flag_publish']=1;
				$worksmain['cdn_host'] = $_lang['cdn_host'];
				
				if (empty($worksmain['flag_from_uc']))
					$worksmain = init_data($worksmain,'worksmain');

				$wid = $Db->insert($Base->table('worksmain'),$worksmain);
				foreach ($imgsmain as $value) {
					$value['pk_atlas_main']=0;
					$value['pk_user_main']=$user['pk_user_main'];
					$value['create_time']=date("Y-m-d H:i:s",Common::gmtime());
					$img_id = $Db->insert($Base->table('imgsmain'),$value);
					$Db->insert($Base->table('imgs_works'),array('pk_img_main' =>$img_id ,'pk_works_main'=>$wid ));
				}
	
				$panoconfig['pk_works_main']=$wid;
				$panoconfig['open_alert']='{}';
				$panoconfig['bg_music']='{"useMusic": false,"isWhole": true}';
				$panoconfig['sky_land_shade']='{ "useShade": false,"isWhole": true}';
				$panoconfig['tour_guide']='{"useStartImg": false,"useEndImg": false,"points": []}';
				$panoconfig['url_phone_nvg']='{}';
				$panoconfig['speech_explain']='{"isWhole": true,"useSpeech": false}';
				$panoconfig['angle_of_view']='{"viewSettings": []}';
				$panoconfig['special_effects']='{}';
				$panoconfig['sand_table']='{"sandTables": [],"isOpen": false}';
				$panoconfig['custom_logo']='{"logoImgPath": "","useCustomLogo": false}';
				$panoconfig['scene_group']='{"sceneGroups": []}';
				$panoconfig['hotspot']='{}';
				$panoconfig['loading_img']='{}';
				$panoconfig['custom_right_button']='{}';
				$panoconfig['custom_menu']='{"menuSettings":[]}';
				
				if (empty($worksmain['flag_from_uc']))
					$panoconfig = init_data($panoconfig,'pano_config');
				$Db->insert($Base->table('pano_config'),$panoconfig);
				foreach ($params['pic_tags'] as  $tid) {
					if ($Db->getCount($Base->table("tag"),"id",array("id"=>$tid,"type"=>1))) {
						$Db->insert($Base->table("tag_works"),array("tag_id"=>$tid,"works_id"=>$wid));
					}
				}
				$Db->commit();
				$re['status'] = 1;
				$re['pid'] = $wid;
				$re['view_uuid'] = $worksmain['view_uuid'];
				$re['thumb_path'] = $worksmain['thumb_path'];
			}catch(Exception $e){
				$Db->rollback();
				print_r($e);
				$re['msg'] = '服务器异常';
			}
		}
		unset($_SESSION['user']['pano_store']);
		echo $Json->encode($re);
		die;
	}
}
else if($act =='keep_alive'){
	//前端循环请求该方法 ，避免切图时造成session丢失
	echo "";
	exit;
}else if($act =='update_init'){
	
	$tag_list = $Db->query("SELECT * FROM ".$Base->table('tag')." WHERE type = 1");
	echo  $Json->encode($tag_list);
	exit;
	
}else{
	$atlas_list = $Db->query("SELECT * FROM ".$Base->table("atlasmain")." WHERE pk_user_main = ".$user['pk_user_main']);
	if(empty($atlas_list)){
		$atlas = array("pk_user_main"=>$user['pk_user_main'],"name"=>"默认图册","atlas_type"=>0,"create_time"=>date('Y-m-d H:i:s',Common::gmtime()));
		//初始化用户图册信息
        $atlas['pk_atlas_main'] = $Db->insert($Base->table("atlasmain"),$atlas);
        $atlas_list[] = $atlas;
	}
	//显示添加页面
	$tp->assign("atlas",$atlas_list);
	$tp->assign("tags",$Db->query("SELECT * FROM ".$Base->table('tag')));
	$tp->assign('title','发布全景');
	$tp->assign('up_url',$_lang['up_url']);
	$tp->assign('img_store_type',$_lang['global_storage']);
}

function init_data($arr,$type){
	$config = $_SESSION['edit'];
	foreach($config as $v){
		if ($v['table']==$type&&isset($v['default'])) {
			$arr[$v['column']] = $v['default'];
		}
	}   
	return $arr;
}

?>